package com.swlz.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Part;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;

import com.alibaba.fastjson.JSONObject;
import com.swlz.commons.DBUtil;
import com.swlz.config.GoFastDfsConfig;
import com.swlz.dao.WebFileDAO;
import com.swlz.entity.WebFile;
import com.swlz.exception.CodeException;
import com.swlz.service.ConfigService;
import com.swlz.service.WebFileService;
import com.swlz.vo.PageVO;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;

/**
 * <pre>
 * 业务逻辑接口具体实现类
 * 网站文件
 * 用于上传文件的记录表
 * ClassName : com.teach.service.impl.WebFileServiceImpl
 * Author : J.L.Zhou
 * E-Mail : 2233875735@qq.com
 * Date : 2020-06-29 08:15:12
 * Version : 1.0
 * Copyright 2020 jlzhou.top Inc. All rights reserved. 
 * Warning: this content is only for internal circulation of the company. It is forbidden to divulge it or use it for other commercial purposes
 * </pre>
 **/
public class WebFileServiceForGoFastDFS implements WebFileService {
	private static Logger log = LoggerFactory.getLogger(WebFileServiceForGoFastDFS.class);
	
	private WebFileDAO webFileDAO = new WebFileDAO();
	private ConfigService configService = new ConfigServiceImpl();
	private GoFastDfsConfig config = configService.getGoFastDfsConfig();
	

	@Override
	public WebFile add(Part file) throws CodeException {
		
		
		

        
		String uri = "";
		Long id = DBUtil.nextId();
		
		InputStreamResource isr = null;
		try {
			isr = new InputStreamResource(file.getInputStream(),
					Long.toString(id,36)+"."+FileUtil.extName(file.getSubmittedFileName()));
		} catch (IOException e) {
			throw new CodeException(500, "读取文件失败！");
		}

        Map<String, Object> params = new HashMap<>();
        params.put("file", isr);
        params.put("path", config.path);
        params.put("output", "json");
        params.put("scene", config.scene);
        params.put("auth_token", config.token);
        String resp = HttpUtil.post(config.server, params);
        
        try{
        	JSONObject obj = JSONObject.parseObject(resp);
        	uri = obj.getString("src");
        }catch(Exception ex){
        	throw new CodeException(500, "保存文件失败！");
        }
        
		WebFile webFile = new WebFile();
		webFile.setFileId(id);
		webFile.setFileContentType(file.getContentType());
		webFile.setFileName(file.getSubmittedFileName());
		webFile.setFileStatus(0);
		webFile.setFileUri(uri);
		try{
			webFileDAO.insert(webFile);
		}catch(Exception ex){
			throw new CodeException(500, "写入数据库失败！");
		}
		
		return webFile;
	}



	@Override
	public int delete(Long fileId) throws CodeException {
		try {
			return webFileDAO.deleteById(fileId);
		} catch (SQLException e) {
			log.warn("删除网站文件错误",e);
			throw new CodeException(502, "删除网站文件错误",e);
		}
	}

	@Override
	public WebFile get(Long fileId) throws CodeException {
		try {
			return webFileDAO.selectById(fileId);
		} catch (SQLException e) {
			log.warn("获取网站文件失败",e);
			throw new CodeException(503, "获取网站文件失败",e);
		}
	}

	@Override
	public PageVO<WebFile> page(WebFile webFile, Integer current, Integer rowMax) throws CodeException {
		try {
			long total = webFileDAO.countByModel(webFile);
			PageVO<WebFile> page = new PageVO<>(total, current, rowMax);
			return page.setList(webFileDAO.selectByModel(webFile, page.getOffset(), page.getRowMax()));
		} catch (SQLException e) {
			log.warn("获取网站文件分页数据失败",e);
			throw new CodeException(504, "获取网站文件分页数据失败",e);
		}
	}

	@Override
	public List<WebFile> list(WebFile webFile, int len) {
		try {
			return webFileDAO.selectByModel(webFile, 0, len);
		} catch (SQLException e) {
			log.warn("获取网站文件列表数据失败",e);
			throw new CodeException(505, "获取网站文件列表数据失败",e);
		}	
	}



	@Override
	public InputStream get(WebFile webFile) throws CodeException {
		HttpResponse res = HttpRequest.get(config.url+webFile.getFileUri()).execute();
		return res.bodyStream();
	}


	@Override
	public String getUrl(WebFile webFile) throws CodeException {
		return config.url+webFile.getFileUri();
	}
	
}
